<template>
	<view class="ag_container">
		<!-- 顶部导航 -->
		<uni-nav-bar :fixed="true" backgroundColor="#00a660" color="#fff" height="90rpx">
			<block slot="left">
				<i class="iconfont nav_backIcon" @click="back()">&#xe8b8;</i>
				<span style="font-size: 30rpx;">指定签章位置</span>
			</block>
			<block slot="right">
				<view class="nav_btn">
					<button @click="save" class="backBtn" size="mini">保存草稿</button>
					<button @click="checkNext" class="nextSign" size="mini">发起签约</button>
				</view>
			</block>
		</uni-nav-bar>
		<uni-data-select v-model="selectValue" :localdata="contractFilename" :clear="false" class="data_select"
			@change="changeContract"></uni-data-select>
    <view class="agree_jn" :class="moveIndex==1?'agree_jn_active':''">
      <view v-if="idx == index" v-for="(file, index) in contractFile" :key="file.id">
        <!-- :class="scaleIndex===0?'bigPdf' : ''" -->
        <view class="drag" :style="{width:widthNum + 'px'}">
          <!-- 合同内容显示 -->
          <pdf ref="pdfRef" :src="file.pdfSrc" v-for="i in file.pageCount" @page-loaded="pageLoad" :page="i"
               style="margin:0 auto 9rpx;"></pdf>
          <view :class="['box', item.boxStamp]" v-for="(item,index) in dropData" @touchmove.prevent
                :style="{transform:`translateX(${item.leftsMobile}px) translateY(${item.topMobile}px)`,zIndex:`${dragZindex}`}"
                @touchstart="dropDatastart" @touchmove="dropDatamove($event,item)">
            <view class="icon" style="user-select: none;font-size: 22rpx;">{{ item.name }}</view>
            <view :class="['controlDesc', item.controlDescMore]" :style="{background:item.color}">
              {{ item.companyName }}
            </view>
            <view class="iconfont del_Area" @click="delSeal(item)" v-if="item.type == 4">
              <i class="iconfont">&#xe6a2;</i>
            </view>
            <view class="iconfont delArea" @click="delSeal(item)" v-else>
              <i class="iconfont">&#xe6a2;</i>
            </view>
          </view>
        </view>
      </view>
    </view>
	
		<uni-fab ref="fab" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
			style="opacity: 0.9;" :direction="direction" :icon="search" @trigger="changeSize" />

		<!-- 签署控件设置 -->
		<uni-collapse @change="moving" :class="moveIndex==1?'uni-collapseMoving':''" class="collapse_bottom">
			<uni-collapse-item titleBorder="none" :border="false" :open="true">
				<template v-slot:title>
					<view class="title_border">
						<span>指定签章位置：
						  <span style="color: #ffffff;" v-show="!isDragAllSet">
							  <i class="iconfont setIcon">&#xe70f;</i>未完成
              </span>
              <span style="color: #ffffff;" v-show="isDragAllSet">
                <i class="iconfont setIcon">&#xe657;</i>已完成
              </span>
            </span>
						<span v-if="moveIndex==1" >完成指定</span>
						<span v-else>去指定</span>
					</view>
				</template>
				<uni-notice-bar single text="按住控件，拖拽到签署位置即可" />
					<scroll-view class="scroll-view_H" scroll-x="true" scroll-left="120">
						<view class="content" v-for="(company,index) in contractFile[idx].contractFileDragList" style="display: inline-block;">
							<view style="display: flex;">
								
							<view style="width: 98%;">
								<view class="vi_coltitle">
									<view class="vi-line" :style="{background:company.color}"></view>
									<view class="tit-fangm flex_between" v-if="company.isStarter==1">
										<view>
											发起方：<span>{{company.signCompany}}</span>
										</view>
										<i class="iconfont">&#xe6d4;</i>
										</view>
									<view class="tit-fangm flex_between" v-else>
										<view>接收方：<span>{{company.signCompany}}</span></view>
										<i class="iconfont">&#xe6d4;</i>
									</view>
								</view>
								<!-- 控件显示 -->
								<view class="mine-actions grid col-4 text-center">
									<view class="action-item" v-for="(item, index) in company.dragList" @touchmove.prevent
										@touchstart="handleTouchstart($event,item)" @touchmove="handleTouchmove"
										@touchend="handleTouchEnd($event,item)">
                    <!-- 页码大于1页 才展示 骑缝章-->
                    <view v-if="contractFile[idx].pageCount>1 && item.type==4 || item.type==3 || item.type==2 ||item.type==1">
                      <i :class="item.iconfont" class="iconfont"></i>
                      <uni-badge :text="item.model" absolute="leftTop"></uni-badge>
                      <text class="text">{{item.name}}</text>
                    </view>
									</view>
								</view>
							</view>
							<view class="bg_white"></view>
							</view>
							</view>
					</scroll-view>	
			</uni-collapse-item>
		</uni-collapse>

		<!-- 企业骑缝章控件弹出框 -->
		<uni-popup ref="popup" background-color="#f7f8f8">
			<view class="popup-content">
				<view class="popup_item">
					<view class="pop_border">
						<p style="margin-top:10rpx;">请选择骑缝章加盖方式</p>
						<uni-data-checkbox v-model="radio1" :localdata="items" style="margin-top:10rpx;">
						</uni-data-checkbox>
					</view>

					<view class="pop_border">
						<p style="margin-top:10rpx;">请选择需要加盖的文件</p>
						<uni-data-checkbox v-model="radio2" :localdata="items_doc" multiple style="margin-top:10rpx;">
						</uni-data-checkbox>
					</view>

					<p style="margin-top:10rpx;">请选择需要加盖的文件</p>
					<uni-data-checkbox v-model="radio3" :localdata="items_last" style="margin-top:10rpx;">
					</uni-data-checkbox>

					<view class="btn_arr">
						<button @click="cancel">取消</button>
						<button @click="confirm">确认</button>
					</view>

				</view>
			</view>
		</uni-popup>
		
		<!-- 确认签约信息弹出 -->
		<confirm-sign-info ref="confirmInfo" :contractInfo="ruleForm" :contractFlow="contractSignFlowList" @submit="nextForm" @ok="getSignSort"></confirm-sign-info>

	</view>
</template>
<script>
	import {selectListPermiss} from "@/api/ec/console/seal/staffSeal";
	import {batchNewContractAndFile,updateContractInfo,} from "@/api/ec/work/contract/contract";
    import pdf from "vue-pdf";
	import config from '@/config';
	import {getContract,getContractFlow,} from "../../api/ec/work/contract/contract";
	import {getWordByContractId,updateContractFileByContractId} from "../../api/ec/work/contract/contractFile";
    import {getToken} from "../../utils/auth";
    import confirmSignInfo from './confirmSignInfo'
	export default {
		components: {pdf,confirmSignInfo},
		data() {
			return {
				hasType:'',//有无印章使用权限 false没有
				isType: this.$store.getters.staffInfo.company, // 判断身份信息 个人还是企业 true企业  false个人
                idx:0,//
				widthNum: '',
				scaleIndex: '', //0放大 1缩小
				flowId: null, //当前签署流程id
				url: "", // pdf 主图
				host: config.baseUrl,
				is_color_type: false,
				search: 'search',
				content: [{
						text: '放大',
						active: false,
					},
					{
						text: '缩小',
						active: false
					},
				],
				directionStr: '垂直',
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'vertical',
				pattern: {
					color: '#3c3e49',
					backgroundColor: '#fff',
					selectedColor: '#00a660',
					buttonColor: '#00a660',
					iconColor: '#fff'
				},
				pdfUrl: '',
				radio1: 0,
				radio2: 0,
				radio3: 0,
				numPages: 0,
				items: [{
					'value': '0',
					'text': '每份文件单独加盖',
				}, {
					'value': '1',
					'text': '多份文件合并加盖'
				}, ],
				items_doc: [{
					'value': '0',
					'text': '电子合同销售文件协议一   （共3页）',
				}, {
					'value': '1',
					'text': '电子合同销售文件协议二   （共5页）'
				}, ],
				items_last: [{
					'value': '0',
					'text': '右边距加盖全部页面（适用单面打印）',
				}, {
					'value': '1',
					'text': '右边距加盖奇数页面，左边距加盖偶数页面（适用双面打印）'
				}, ],
				contractFile: [],
				contractFilename: [],
				selectValue: 0, //切换合同value
				moveIndex: 1, //折叠框移动
				// 印章相关字段
				dropData: [], // 拖拽数据
                dropDataCache:new Map(),//拖拽的缓存数据
				dragDataTemp: {}, // 当前拖拽临时对象
                dragSetNumber:0,// 控件设置的总数
				// 距离右边距
				rightFixedWidth: 0, // 动态获取印章的 宽度
				// 骑缝章右边距
				rightFixedWidthPage: 50, // 动态获取
				dragOffsetX: 50, // 拖拽偏移量x 由于页面定位下移 导致按下的位置偏移
				dragOffsetY: 230, // 拖拽偏移量y
				dragZindex: 0, // 动态设置控件层级
                isDragAllSet: false,// 是否全部设置完成
				pdfWidth: '',
				pdfHeight: '',
				dpi: 96, // 此处dpi暂时写死 移动端盖章dpi暂时不适用 盖章参数 已转换成pc端参数
				contractId: 0,
				ruleForm: '',
				contractSignFlowList: [],
				dragList: [{
						id: null,
						ids: null,
						name: '印章控件',
						width: 50,
						height: 50,
						lefts: 0,
						top: 0,
						leftsMobile: 0,
						topMobile: 0,
						type: 1,
						model: '',
						status: '未设置',
						statusColor: 'color:red',
						statusIcon: 'icon-gantanhao-quan',
						companyName: '',
						dataId: 0, //控件属于公司 个人id
						iconfont: 'icon-yinzhang',
						dpi: 0, //屏幕分辨率
						pdfHeight: 0,
						numPages: 0, //pdf总页码
					},
					{
						id: null,
						ids: null,
						name: '签字章控件',
						width: 50,
						height: 50,
						lefts: 0,
						top: 0,
						leftsMobile: 0,
						topMobile: 0,
						type: 2,
						model: '',
						status: '未设置',
						statusColor: 'color:red',
						statusIcon: 'icon-gantanhao-quan',
						companyName: '',
						dataId: 0,
						iconfont: 'icon-wofuzedehetong',
						dpi: 0,
						pdfHeight: 0,
						numPages: 0, //pdf总页码
					},
					{
						id: null,
						ids: null,
						name: '日期控件',
						lefts: 0,
						top: 0,
						leftsMobile: 0,
						topMobile: 0,
						type: 3,
						model: '',
						status: '未设置',
						statusColor: 'color:red',
						statusIcon: 'icon-gantanhao-quan',
						companyName: '',
						dataId: 0,
						iconfont: 'icon-rili-xianxing-xi',
						dpi: 0,
						pdfHeight: 0,
						numPages: 0, //pdf总页码
					},
					{
						id: null,
						ids: null,
						name: '骑缝章控件',
						width: 50,
						height: 50,
						lefts: 0,
						top: 0,
						leftsMobile: 0,
						topMobile: 0,
						type: 4,
						model: '',
						status: '未设置',
						statusColor: 'color:red',
						statusIcon: 'icon-gantanhao-quan',
						companyName: '',
						dataId: 0,
						iconfont: 'icon-qifengzhang',
						dpi: 0,
						pdfHeight: 0,
						numPages: 0, //pdf总页码
					},
				],
				colorList: ['#00a660', '#276ef9', '#ff7d00', '#ec417a', '#ac47bb', '#8E6d63', '#00736d', '#f29876',
					'#ac6a00', '#638c0b'
				],
        needToDragNumber:null,
			};
		},
		onLoad(options) {
      if (!!options.id) {
				this.contractId = options.id;
			} else {
				//fixme 测试使用
				this.contractId = 2773
			}
			// uni.showLoading({
			// 	title: '加载中',
			// 	mask: true
			// });
			this.initData();
		},
    watch: {
      dropData: {
        handler(dragList, oldValue) {
          // 保存最新的控件状态
          this.dropDataCache.set('companyControlsStatus' + this.idx, dragList);
          // 重复拖拽提示
          let map = dragList.map(e => e.dataId + "@" + e.type);
          if ((new Set(map)).size != map.length) {
            //this.$modal.msg("重复控件");
          }
          let setNumber = 0;// 记录已经设置的控件总数
          this.dropDataCache.forEach(cache => {
            setNumber += cache.length;
          })
          this.dragSetNumber = setNumber;
          // 需要拖拽的控件 等于已经拖拽的控件数量 则是全部已经设置完成
          if (this.needToDragNumber == setNumber) {
            this.isDragAllSet = true;
          } else {
            // 控件设置不够
            this.isDragAllSet = false;
          }
        },
      },
      immediate: false,
      deep: true
    },
	methods: {
      // 统计有多少个需要拖拽的控件
      needDragNumberMethod(fileList){
        let dragNumber = 0;// 记录需要拖拽的总数
        fileList.forEach(file => {
          file.contractFileDragList.forEach(contractFileDrag => {
            // 判断是否刷新页面 重新加载
            if (!!contractFileDrag.dragList) {
              // 这里要计算多文件骑缝章个数问题 骑缝章类型*文件数
              for (let i = 0; i < contractFileDrag.dragList.length; i++) {
                let drag = contractFileDrag.dragList[i];
                //若文件页码为1 则排除骑缝章
                if (file.pageCount == 1 && drag.type == 4) {
                  continue;
                }
                // 若pdf页码大于1页并且 是骑缝章
                if (file.pageCount > 1 && drag.type == 4) {
                  dragNumber += file.pageCount;
                } else {
                  dragNumber += 1
                }
              }
            }
          })
        })
        return dragNumber;
      },
			/** 切换合同 */
      changeContract(e) {
        // 当前切换合同和上一个合同是同一个 防止重复点击
        if(this.idx==e){
          return;
        }
        // 切换其他文件
        this.idx = e;
        // 加载缓存文件
        this.initFilePosition(this.idx);
        // 清空
        this.dropData = [];
        this.$modal.loading();
        // 拿到当前文件的所有控件
        let json = this.dropDataCache.get('companyControlsStatus' + this.idx);
        if (!!json) {
          // 不为空 回显到显示层
          this.dropData = json;
        }
      },
		initData() {
        // 初始合同信息
        getContract(this.contractId).then((response) => {
          this.ruleForm = response.data;
        }).then(() => {
          // 初始 合同印章控件
          getWordByContractId(this.contractId).then((response) => {
            // 拼接缩略图
            response.data.forEach((item,index) => {
              this.contractFilename.push({
                value: index,
                text: item.name,
                path: item.path
              });
              this.contractFile.push(item);
              // 0 在线模板 1本地文档
              // 默认选中第一个文件
              if (index == 0) {
                this.selectValue = this.contractFilename[0].value
                this.numPages = item.pageCount;
                // 解密并读取pdf文件
                item.pdfSrc = this.host + "/ec/contract/decryptContractByMobile?path="+item.path + "&keyId=" + this.ruleForm.contractNumber+"&token="+getToken();
              }
              item.pdfSrc = this.host + "/ec/contract/decryptContractByMobile?path="+item.path + "&keyId=" + this.ruleForm.contractNumber+"&token="+getToken();
            });

            return this.pdfUrl;
          }).then((response) => {
            // this.getNumPages(response);
          })
		  // 印章使用权限
		  selectListPermiss().then((response) => {
		  	this.hasType = response.data
		  });
        });
			},
			/** 放大缩小 */
			changeSize(e) {
				// 放大
				if (e.index == 0) {
					let dragWidth = document.getElementsByClassName("drag")[0].clientWidth
					this.widthNum = dragWidth + 50
				} else if(e.index == 1){
					// 缩小
					let dragWidth = document.getElementsByClassName("drag")[0].clientWidth
					if (dragWidth > document.getElementsByClassName('agree_jn')[0].clientWidth) {
						this.widthNum = dragWidth - 50
					}
				}
			},
			delSeal(item) {
				// 删除
				this.delSealItem(item);
			},
			delSealItem(item) {
        // 骑缝章删除
        if (item.type == 4) {
          // 保留不是当前公司的骑缝章 或者 不是印章 签名 和时间章
          this.dropData = this.dropData.filter(e => item.dataId!=e.dataId || e.type==1 || e.type==2 || e.type==3);
        } else {
          this.dropData.splice(this.dropData.indexOf(item), 1);
        }
				// 删除显示的数量
				this.contractSignFlowList.forEach(dragList => {
					let drag = dragList.dragList.find(drag => drag.ids == item.ids);
					if (!!drag) {
						drag.model -= 1;
					}
				})
			},
			dropDatastart(e) {
				let page = e.changedTouches[0];
				// 上一次初始 位置
				this.pageX = page.pageX;
				this.pageY = page.pageY;
				// console.log('start:', page.pageX,page.pageY);
			},
			dropDatamove(e, item) {
				let {
					pageX,
					pageY
				} = this;
				// 触摸位置
				let page = e.changedTouches[0];
				let dragOffsetY = this.dragOffsetY;
				if (item.type == 2 || item.type == 3) {
					dragOffsetY = dragOffsetY - 30;
				}
				// 算出鼠标相对元素的位置
				const disX = page.pageX - pageX + this.dragOffsetX;
				const disY = page.pageY - pageY + dragOffsetY;
				this.pageX = page.pageX;
				this.pageY = page.pageY;
				let lefts = page.pageX - disX;
				let top = page.pageY - disY;
				// 宽度设置
				if (lefts >= this.pdfWidth - this.rightFixedWidth) {
					lefts = this.pdfWidth - this.rightFixedWidth
				}
				// 限制左边距
				if (lefts <= 0) {
					lefts = 0
				}
				// 设置 上边距
				if (top <= this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop) {
					top = this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop
				}

				// 设置 下边距
				if (item.type == 3) {
					// 日期插件 高度下边界限制
					if (top >= this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop + this.pdfHeight - this
						.rightFixedWidth + (this.rightFixedWidth / 1.3)) {
						top = this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop + this.pdfHeight - this
							.rightFixedWidth + (this.rightFixedWidth / 1.3);
					}
				} else if (item.type == 2) {
					//签名 下边界 高度设置
					if (top >= this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop + this.pdfHeight - this
						.rightFixedWidth + (this.rightFixedWidth / 1.4)) {
						top = this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop + this.pdfHeight - this
							.rightFixedWidth + (this.rightFixedWidth / 1.4);
					}
				} else {
					// 企业印章 高度限制
					// 高度设置  不能超过当前页码的高度
					if (top >= this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop + this.pdfHeight - this
						.rightFixedWidth) {
						top = this.$refs.pdfRef[item.currentPage - 1].$el.offsetTop + this.pdfHeight - this
						.rightFixedWidth;
					}
				}

				//骑缝章上下托
				if (item.type == 4) {
					if (lefts <= this.pdfWidth - this.rightFixedWidth + (this.rightFixedWidth / 1.4)) {
						lefts = item.leftsMobile
					}
				}

				// 高度限制
				item.topMobile = top
				// 左边距限制  赋值
				item.leftsMobile = lefts;
			},
			// pdf已经加载的页码数
			pageLoad(e) {
				// 加载第一页就开始计算
				if (e == 1) {
					// 生成的单页 pdf 宽度 分辨率不同 宽度不同
					this.pdfWidth = this.$refs.pdfRef[0].$el.offsetWidth;
					// 生成的单页 pdf 宽度 分辨率不同 宽度不同
					this.pdfHeight = this.$refs.pdfRef[0].$el.offsetHeight
					// 动态获取印章 css宽度
					this.rightFixedWidth = (this.pdfWidth / 796) * 168;
          this.$modal.closeLoading()
          // 默认加载第一个拖拽数据 延迟监听dropData 改变事件
          setTimeout(() =>{
            this.initFilePosition(this.idx);
          },500)
          // 初始化流程信息
          this.initcontractFlow();
				}
			},
      // 初始化位置 和缓存 index文件索引
			initFilePosition(index) {
				if (!!this.contractFile[index].contentPosition) {
					// 根据pc端定位 计算mobile端 定位
					let dropTemp = JSON.parse(this.contractFile[index].contentPosition);
					dropTemp.forEach(drop => {
						drop.leftsMobile = (drop.lefts / 796) * this.pdfWidth
						drop.topMobile = (drop.top / 1125) * this.pdfHeight
					});
					this.dropData = dropTemp;
          this.dropDataCache.set('companyControlsStatus' + index, 	this.dropData);
				}
			},
			initcontractFlow() {
				// 查询合同流程详情
				getContractFlow(this.contractId).then((response) => {
					this.contractSignFlowList = response.data;
					// 根据合同流程 初始化 控件信息
					for (let i = 0; i < this.contractSignFlowList.length; i++) {
						let item = this.contractSignFlowList[i];
						for (let j = 0; j < this.dragList.length; j++) {
							let drag = this.dragList[j];
							let newData = JSON.parse(JSON.stringify(drag));
							newData.ids = Math.random();
							newData.model = 0; // 已经设置的控件数量
							newData.companyName = item.signCompany;
                            // 签署流程id
                            newData.flowId = item.id;
							// 控件所属数据Id fixme 此处判断 当前控件的信息 是个人还是公司
							if (item.signerType == 0) {
								newData.dataId = item.systemCompanyId;
							} else {
								newData.dataId = item.systemStaffId;
								// 个人不展示骑缝章
								if (newData.type === 4) {
									continue;
								}
							}
							//如果是单页合同 就不展示骑缝章
							// if (newData.type === 4 && this.numPages === 1) {
							// 	continue;
							// }
							// 如果是个人
							if (newData.type === 1 && item.systemCompanyId === 0) {
								continue;
							}
							// 给拖拽控件添加颜色框
							newData.color = this.colorList[i];
							item.dragList.push(newData);
						}
						item.color = this.colorList[i];
						// 赋值当前签署流程id 判断当前登录用户是企业还是个人 再进行流程赋值 pc版本同步修改 此处出现的问题是 当前账号企业身份给自己的个人身份发起合同 出现bug
						// 个人
						if (this.$store.getters.staffInfo.companyId == 0) {
							if (this.$store.getters.staffInfo.id == item.systemStaffId) {
								this.flowId = item.id;
							}
						} else {
							// 企业
							if (this.$store.getters.companyInfo.id == item.systemCompanyId) {
								this.flowId = item.id;
							}
						}
					}
          // 把公司信息复制一份 放到 文件公司控件字段中  普通合同和标准合同授权人是否需要签名
          this.contractFile.forEach(file=>{
            // 公司初始流程数据 
            let contractSignFlow = JSON.parse(JSON.stringify(this.contractSignFlowList));
            contractSignFlow.forEach(e => {
              // 在线模板文件类型 且是企业  且设置了限制为0 不使用授权人签字
              if (file.fileType == 0 && e.signerType == 0 && e.isCompanySignHtml==0) {
                e.dragList = e.dragList.filter(k => k.type != 2);
              }
              // 本地上传文件类型 且是企业  且设置了限制为0 不使用授权人签字
              if (file.fileType == 1 && e.signerType == 0 && e.isCompanySign==0) {
                e.dragList = e.dragList.filter(k => k.type != 2);
              }
            })
            file.contractFileDragList = contractSignFlow;
          });
          // 计算要拖拽多少个控件数量 才能设置为 已完成
          this.needToDragNumber = this.needDragNumberMethod(this.contractFile);
					// this.checkSetStatus();
				});
			},
			handleTouchstart(ev, data) { // 初始拖拽 
				let page = ev.changedTouches[0];
				// 设置层级
				this.dragZindex = 9999;
				// 显示只点击一下 进行拖拽
				this.dragDataTemp = JSON.parse(JSON.stringify(data));
				// 拖拽控件的初始化数据
				this.dragDataTemp.dpi = this.dpi;
				this.dragDataTemp.numPages = this.numPages;
				this.dragDataTemp.id = Math.random();
				// this.dragDataTemp = {lefts: page.pageX - 40, top: page.pageY - 120, ids: genDateUUID(3),name:data.name};
				// 拖拽向左偏移
				this.dragDataTemp.leftsMobile = page.pageX - this.dragOffsetX;
				// 拖拽向下偏移
				let dragOffsetY = this.dragOffsetY;
				if (this.dragDataTemp.type == 2 || this.dragDataTemp.type == 3) {
					dragOffsetY = dragOffsetY - 30;
				}
				this.dragDataTemp.topMobile = page.pageY - dragOffsetY;
				this.dragDataTemp.currentPage = this.calSelectPage(page.pageY + dragOffsetY);
				// 姓名样式
				if (data.type == 2) {
					this.dragDataTemp.boxStamp = "nameSeal";
					this.dragDataTemp.controlDescMore = "controlDescname"
				}
				// 时间控件样式
				if (data.type == 3) {
					this.dragDataTemp.boxStamp = "timeSeal";
					this.dragDataTemp.controlDescMore = "controlDesctime"
				}
				// 企业印章控件
				if (data.type == 1) {
					this.dragDataTemp.controlDescMore = "controlDescOne"
				}
				// 骑缝印章控件
				if (data.type == 4) {
					this.dragDataTemp.boxStamp = "pageSeal";
					this.dragDataTemp.controlDescMore = "controlDescpage";
				}
				this.dropData.push(this.dragDataTemp);
			},
			handleTouchmove(ev) { // 初始拖拽中
				this.dragZindex = 9999;
				let {
					pageX,
					pageY,
					top,
					lefts
				} = this;
				let page = ev.changedTouches[0];
				// 控件高度不同 设置不同的偏移量
				let dragOffsetY = this.dragOffsetY;
				if (this.dragDataTemp.type == 2 || this.dragDataTemp.type == 3) {
					dragOffsetY = dragOffsetY - 30;
				}
				const disX = page.pageX - pageX + this.dragOffsetX;
				const disY = page.pageY - pageY + dragOffsetY;
				this.pageX = page.pageX;
				this.pageY = page.pageY;
				// 限制骑缝章放置区域
				if (this.dragDataTemp.type == 4) {
					this.dragDataTemp.leftsMobile = this.pdfWidth - (this.rightFixedWidth / 2.5);
				} else {
					this.dragDataTemp.leftsMobile = page.pageX - disX;
				}
				this.dragDataTemp.topMobile = page.pageY - disY;
				// 拖拽后 计算当前盖章的页码
				this.dragDataTemp.currentPage = this.calSelectPage(page.pageY - dragOffsetY);
			},
			handleTouchEnd(ev,item) { // 初始结束  限制 拖动的距离
				this.dragZindex = 0;
				let page = ev.changedTouches[0];
				let view = uni.createSelectorQuery().in(this).select(".ag_container");
				setTimeout(() => {
					view.boundingClientRect(data => {
						if (page.pageY < this.dragOffsetY - data.top) {
              // 若拖出边界 则进行删除
							this.dropData.splice(this.dropData.indexOf(this.dropData.find(data => data.id == this.dragDataTemp.id)), 1);
						} else {
							// 放置控件成功
							this.contractSignFlowList.forEach(dragList => {
								let drag = dragList.dragList.find(drag => drag.ids == this.dragDataTemp.ids);
								if (!!drag) {
									drag.model += 1;
								}
							});
              // 若是骑缝章  根据页码数量 复制骑缝章数量
              if (item.type == 4) {
                // 排除当前正在拖拽的骑缝章 不能删除其他签署方的骑缝章 因要重新进行组装
                this.dropData.splice(this.dropData.indexOf(this.dropData.find(data => data.dataId == item.dataId && data.type === 4)), 1);
                // 骑缝章检查重复
                if (this.checkPageSealSet(item)) {
                  return false;
                }
                let selectPage = this.calSelectPage(page.pageY - this.dragOffsetY);
                // 计算落点位置
                let  topTemp = ((page.pageY / selectPage) - 230);// 算出相对第一页位置高度
                // 移除当前操作的骑缝章
                let view = uni.createSelectorQuery().in(this).select(".drag");
                let pdfOneHeignt = view._component.$refs.pdfRef[0].$el.clientHeight;// 获取单页pdf高度
                let pageSealfixPX = 0;
                for (let i = 1; i <= this.contractFile[this.idx].pageCount; i++) {
                  let newData = JSON.parse(JSON.stringify(item));
                  // 骑缝章 距左边界
                  newData.leftsMobile = this.pdfWidth - 35
                  // 骑缝 高度 由于每页间隔10px 递增页码时候 增加10px
                  newData.topMobile = topTemp+ (pdfOneHeignt * (i - 1));
                  newData.boxStamp = "pageSeal";
                  newData.controlDescMore = "controlDescpage";
                  newData.currentPage = i;
                  this.dropData.push(newData)
                }
              }
						}
					}).exec();
				}, 50);
			},
    checkPageSealSet(data) {
      for (let i = 0; i < this.dropData.length; i++) {
        let dropData = this.dropData[i];
        if (dropData.type == 4 && dropData.dataId == data.dataId) {
          this.$modal.msgError("当前公司已经设置过骑缝章！");
          return true;
        }
      }
    },
			// 计算当前拖拽后的页码
			calSelectPage(input) {
				this.selectPage = Math.ceil(input / this.$refs.pdfRef[0].$el.offsetHeight);
				console.log("盖章页码" + this.selectPage)
				return this.selectPage;
			},
			handleBuilding() {
				alert(1)
			},
			getNumPages(url) {
				let loadingTask = pdf.createLoadingTask(url);
				loadingTask.promise.then((pdf) => {
					this.numPages = pdf.numPages;
				});
			},
			/**折叠框移动*/
			moving(e) {
				// moveIndex判断是否展开
				if (e.length != 0) {
					this.moveIndex = 1
					// 折叠打开 修改 按键偏移量
					this.dragOffsetY = 230;
				} else {
					this.moveIndex = 0
					this.dragOffsetY = 130;
				}
			},
			/**取消*/
			cancel() {
				this.$refs.popup.close()
			},
			/**确认*/
			confirm() {
				this.$refs.popup.close()
			},
			/**企业骑缝章控件*/
			comcontrol() {
				this.$refs.popup.open()
			},
			/** 保留草稿 */
			save() {
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})
				// 把相对位置 改为 796  1125
        this.dropDataCache.forEach(cache => {
          cache.forEach(drop => {
            drop.lefts = (drop.leftsMobile / this.pdfWidth) * 796;
            drop.top = (drop.topMobile / this.pdfHeight) * 1125;
          })
        })
				// 修改合同文件
				this.contractFile.contractId = this.ruleForm.id;
        this.contractFile.forEach((file, index) => {
          // 取出缓存的控件
          let dragJson = this.dropDataCache.get("companyControlsStatus" + index)
          if (!!dragJson) {
            file.contentPosition = JSON.stringify(dragJson);
          }
        });
				updateContractFileByContractId(this.contractFile).then(() => {
					// 点击完成签署 更新 当前签署流程状态 盖章完成
					// this.ruleForm.status = 4;
					// // 合同开始签署
					// this.ruleForm.signStatus = 1;
					// // 保存合同签署流程控件状态
					// this.ruleForm.contractSignFlowList = this.contractSignFlowList;
					// updateContractInfo(this.ruleForm).then(response => {
					// });
					// // 企业但没有签署权限
					// if (this.isType == true && this.hasType == false) {
					//   pushContractView(5, this.ruleForm.id, this.flowId,)
					// } else if (this.isType == true && this.hasType == true) {
					//   // 企业有签署权限
					//   pushContractView(4, this.ruleForm.id, this.flowId,)
					// }
					// // 个人有签署权限
					// if (this.isType == false) {
					//   pushContractView(4, this.ruleForm.id, this.flowId,)
					// }
				});
				setTimeout(() => {
				  uni.switchTab({
				    url: '/pages/index'
				  })
				}, 1000)
			},
			/** 返回 */
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
      currentDataId() {
        if (this.$store.getters.staffInfo.companyId != 0) {
          return this.$store.getters.staffInfo.companyId;
        } else {
          return this.$store.getters.staffInfo.id;
        }
      },
      // 检查控件设置完成
      checkControlStatus() {
        // 已经拖拽的控件数目
        if (this.dragSetNumber!= this.needToDragNumber ) {
          this.$modal.msgError('签署控件未设置完毕！');
          return false;
        }
        return true;
      },
	  nextForm(){
		  // 检查控件设置状态
      this.$modal.loading("加载中，请稍候...");
      // 把相对位置 改为 796  1125
      this.dropDataCache.forEach(cache => {
        cache.forEach(drop => {
          drop.lefts = (drop.leftsMobile / this.pdfWidth) * 796;
          drop.top = (drop.topMobile / this.pdfHeight) * 1125;
        })
      })
      this.contractFile.contractId = this.ruleForm.id;
      this.contractFile.forEach((file, index) => {
        // 取出缓存的控件
        let dragJson = this.dropDataCache.get("companyControlsStatus" + index)
        if (!!dragJson) {
          file.contentPosition = JSON.stringify(dragJson);
        }
      });
		  // 点击完成签署 更新 当前签署流程状态 盖章完成
		  this.ruleForm.status = 4;
		  // 合同开始签署
		  this.ruleForm.signStatus = 1;      
		  // 保存合同签署流程控件状态
		  this.ruleForm.contractSignFlowList = this.contractSignFlowList;
		  // 根据当前签署流程 判断是否存在批量签署 若存在批量签署走批量签署接口 若不存在走单独签署接口
		  let isHaveBatchPerson = this.contractSignFlowList.find(e=>e.isBatch==1);// 存在批量个人签署或者批量企业签署
		  if (isHaveBatchPerson) {
		    let data = {};
		    // 合同信息
		    data.contractDTO = this.ruleForm;
		    // 签署文件
		    data.contractFiles = this.contractFile;
		    batchNewContractAndFile(data).then((response) => {
		  	this.$modal.closeLoading()
		      // 跳转到待我签署
		     uni.navigateTo({
		     	url:'/pages/common/contractManage/contractSign/listMe'
		     })
		    });
		  }
		  
		  //当前签署流程不存在批量签署
		  if (!isHaveBatchPerson){
		    // 二次检查控件定位
		    updateContractFileByContractId(this.contractFile).then(() => {
		      updateContractInfo(this.ruleForm).then(response => {
		      }).then(()=>{
		        this.$modal.closeLoading()
		        // 如果盖章人不是当前用户 当前用户是经办人 直接跳转到合同详情页 等待盖章人盖章
		        let isStarterSignFlow = this.contractSignFlowList.find(signFlow =>signFlow.isStarter==1);
		        // 如果发起人的流程顺序不为0 则说明顺序调整了 则跳转到 待他方处理首页
		        if (isStarterSignFlow.signerSort != 0) {
		          this.$modal.alert("请先等待【接收方】签署文件后，【发起方】再进行签署。");
		          uni.switchTab({
		          	url:'/pages/index'
		          })
		          return;
		        }
		        // 当前用户就是经办人  经办人不等于盖章人
		        if (this.$store.getters.staffInfo.id != isStarterSignFlow.sealerId) {
		  		uni.navigateTo({
		  			url:'./detail?id='+this.ruleForm.id
		  		})
		          return;
		        }
		        // 企业但没有签署权限
		        if (this.isType == true && this.hasType == false) {
		  		  uni.navigateTo({
		  		  	url:'./detail?id='+this.ruleForm.id+'&flowId='+this.flowId
		  		  })
		          return;
		        } else if (this.isType == true && this.hasType == true) {
		          // 企业有签署权限
		  		uni.navigateTo({
		  			url:'./signedByme?id='+this.ruleForm.id+'&flowId='+this.flowId
		  		})
		          return;
		        }
		        // 个人有签署权限
		        if (this.isType == false) {
		  		uni.navigateTo({
		  			url:'./signedByme?id='+this.ruleForm.id+'&flowId='+this.flowId
		  		})  
		          return;
		        }
		      });
		    });
		  }    
	  },
			/**下一步 */
			checkNext() {
				if (!this.checkControlStatus()) {
				  return false;
				}
				this.$refs.confirmInfo.openDialog()
			},
		},
	};
</script>

<style lang="scss" scoped>
	::v-deep .uni-navbar__header-btns-left {
	  width: 220rpx !important;
	}
	
	::v-deep .uni-navbar__header-btns-right {
	  width: 420rpx !important;
	}
	.nextSign {
	  background: $uni-color-primary;
	  color: #fff;
	  border: solid 1rpx #fff;
	  height: 55rpx;
	  line-height: 55rpx;
	  margin-left: 20rpx;
	}
	::v-deep .uni-badge--error{
		background: $uni-color-primary;
	}
	.setIcon{
		font-size: 24rpx;
		margin-right: 8rpx;
	}
	.bg_white{
		background: #fff;
		width: 20rpx;
		height: 216rpx;
	}
	.tit-fangm {
		margin-left: 15rpx;
		font-size: 28rpx;
		width: 100%;

		span {
			font-size: 24rpx;
			color: #666666;
		}
	}
	.scroll-view_H {
			white-space: nowrap;
			width: 100%;
			background: #f1f5f3;
		}

	.vi-line {
		width: 8rpx;
		height: 24rpx;
		background-color: red;
		content: '';
		border-radius: 10rpx;
	}

	.vi_coltitle {
		display: flex;
		align-items: center;
		width: 100%;
		height: 80rpx;
		padding: 0 25rpx;
	}

	.title_border {
		height: 70rpx;
		line-height: 70rpx;
		color: #fff;
		padding-left: 30rpx;
		background: $uni-color-primary;
		width: 100%;
		display: flex;
		justify-content: space-between;
	}

	.nameSeal {
		height: 48rpx !important;
	}

	.timeSeal {
		height: 40rpx !important;
	}

	.pageSeal {
		width: 65rpx !important;
	}

	.delArea {
		//opacity: 0;
		z-index: 2;
		position: absolute;
		top: -70rpx;
		right: 60rpx;
		color: red;
	}
	.del_Area{
		z-index: 2;
		position: absolute;
		top: -40rpx;
		right: 20rpx;
		color: red;
	}

	.controlDesc {
		position: absolute;
		// background:#cbe6f3;
		background: #7faaff;
		border: 1px solid #e8e8e8;
		top: -20px;
		height: 32rpx;
		width: 160rpx;
		color: #fff;
		font-size: 12px;
		text-align: center;
		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
		-webkit-box-orient: vertical;
		//显示行数:;
		-webkit-line-clamp: 1;
		border-radius: 2px;
		-webkit-border-radius: 2px;
		-moz-border-radius: 2px;
		-ms-border-radius: 2px;
		-o-border-radius: 2px;
	}

	// 企业骑缝章控件
	.controlDescpage {
		position: absolute;
		background: #7faaff;
		border: 1rpx solid #e8e8e8;
		top: -1px !important;
		text-align: center;
		width: 32rpx;
		position: absolute;
		right: 70rpx;
		color: #fff;
		writing-mode: vertical-rl;
		letter-spacing: 2px;
		height: 155rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		// -webkit-box-orient: vertical;
		// -webkit-line-clamp: 1; //显示行数
		// display: -webkit-box; /*作为弹性伸缩盒子模型显示*/
	}

	.drag {
		position: relative;

		.box {
			border: 1px dashed #125ef7;
			position: absolute;
			user-select: none;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			border-radius: 5px;
			width: 158rpx;
			height: 158rpx;
			background: #f1f1f1;
			opacity: 0.9;
			left: 0;
			top: 0;
		}
	}

	.collapse_bottom {
		background: $uni-color-primary;
		position: fixed;
		bottom: 0;
	}

	.uni-collapseMoving {
		background: $uni-color-primary;
		position: fixed;
		top: 0;
		bottom: 100%;
		z-index: 999;

	}

	::v-deep .uni-data-checklist .checklist-group .checklist-box {
		margin-right: 50rpx;
	}

	uni-swiper {
		height: 240rpx;
	}

	::v-deep .uni-icons {
		color: #fff !important;
	}

	::v-deep .uni-fab__circle--rightBottom {
		bottom: 200rpx;
		right: 50rpx;
		z-index: 0;
	}

	::v-deep .uni-fab--rightBottom {
		bottom: 200rpx;
		right: 50rpx;
		z-index: 0;
	}

	::v-deep .uni-section .uni-section-header__content-sub {
		color: #666666 !important;
	}

	::v-deep .uni-section .uni-section-header__content {
		flex-direction: row;
	}

	::v-deep .uni-section .uni-section-header {
		padding: 16rpx 20rpx;
	}

	::v-deep .uni-noticebar__content-text--single {
		text-align: center;
		font-size: 26rpx;
	}

	::v-deep .uni-noticebar {
		padding: 10rpx 0;
		margin-bottom: 0;
	}

	::v-deep .uni-section .uni-section-header__decoration {
		background: $uni-color-primary;
	}

	::v-deep .uni-collapse-item__title-box {
		height: 70rpx;
		line-height: 70rpx;
	}

	::v-deep .uni-collapse-item__title {
		background: $uni-color-primary;
	}

	::v-deep .uni-collapse-item__title-text {
		color: #fff;
	}

	.uni-data-checklist .checklist-group .checklist-box {
		margin: 6rpx 0;
	}

	.popup-content {
		width: 600rpx;
		height: 730rpx;

		.popup_item {
			padding: 20rpx 40rpx;
			font-size: 26rpx;

			.pop_border {
				padding-bottom: 20rpx;
				border-bottom: 1rpx solid #dcdcdc;
			}
		}

		.uni-label-pointer,
		p {
			color: #666666;
			font-size: 24rpx;
			display: block;
		}
	}

	.action-item {
		margin-top: 16rpx;

		.iconfont {
			font-size: 40rpx;
			border-radius: 10rpx;
			border: solid 1rpx #d2d2d2;
			padding: 10rpx;
			color: #adadad;
		}

		.text {
			display: block;
			font-size: 24rpx;
			margin: 6rpx 0rpx;
			color: #666666;
		}
	}


	.uni-collapse {
		background: $uni-color-primary;
	}

	.content {
		// background: #dcdcdc !important;
		width: 90%;
		// overflow-y: scroll;
		display: flex;
		height: 216rpx;

		.uni-forms_flex {
			display: flex;
			align-items: center;

			.flex_input {
				margin-right: 20rpx;
			}
		}
	}

	.border {
		margin-top: 10rpx;
		border: 1rpx solid #cccccc;
	}

	page {
		background: $uni-bg-color;
	}

	.ag_container {
		position: relative;
	}

	.agree_jn {
		padding: 90rpx 0rpx 0;
		background-color: #fff;
		width: 100%;
		overflow-x: scroll;
	}

	.agree_jn_active {
		padding: 280rpx 0rpx 0;
		width: 100%;
		overflow-x: scroll;
		background-color: #fff;
	}
</style>
